package com.dsx.myblog.service.impl;

import com.dsx.myblog.dao.ArticleMapper;
import com.dsx.myblog.entity.Article;
import com.dsx.myblog.entity.ArticleExample;
import com.dsx.myblog.service.ArticleService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author dsx
 */
@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleService articleService;

    @Override
    public List<Article> list(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        ArticleExample example = new ArticleExample();
        example.setOrderByClause("id desc");
        return articleMapper.selectByExample(example);
    }

    @Override
    public void add(Article article) {
        articleMapper.insert(article);
    }

    @Override
    public void delete(long id) {
        articleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Article get(long id) {
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Article article) {
        articleMapper.updateByPrimaryKey(article);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void testTransactional() {
        Article article = new Article();
        article.setId(1L);
        article.setContent("测试事务");
        articleMapper.updateByPrimaryKeySelective(article);
        articleService.updateArticle2();
        throw new RuntimeException("测试回滚");

    }

    @Override
    @Transactional(rollbackFor = Throwable.class, propagation =  Propagation.REQUIRES_NEW)
    public void updateArticle2(){
        Article article = new Article();
        article.setId(2L);
        article.setContent("测试事务");
        articleMapper.updateByPrimaryKeySelective(article);


//        ThreadLocal
    }

    public static void main(String[] args) {
        String str1 = "hello";                 // 引用常量池中的字符串
        String str2 = "hello";                 // 复用常量池中的字符串
        String str3 = new String("hello");     // 在堆中创建新的字符串对象
        String str4 = new String("hello");     // 再次在堆中创建新的字符串对象

        // 比较内存地址
        System.out.println(str1 == str2);      // true, 因为 str1 和 str2 引用常量池中的同一对象
        System.out.println(str1 == str3.intern());      // false, 因为 str3 引用堆中的新对象
        System.out.println(str3 == str4);      // false, 因为 str3 和 str4 是堆中的两个不同对象
    }

}
